import { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { ArrowLeft } from 'lucide-react';
import '../pages/GeometryModelView.css';
import './SpecialModelBase.css';
import './TwoTrianglesIntersection.css';

/**
 * TwoTrianglesIntersection 特殊模板
 * 演示两个三角形的交点关系（杠杆模型）
 * 功能：
 * 1. 上面的小三角形 ADE（A为中心，D在右上，E在左上）
 * 2. 下面的三角形 ABC（A为中心，B在左下，C在右下）
 * 3. BD 固定不动
 * 4. CE 可拖动，但必须保持同一条线（如同杠杆，A为支点）
 * 5. ADE 面积比 ABC 小
 */

function TwoTrianglesIntersection({ modelTitle }) {
  const navigate = useNavigate();
  const canvasRef = useRef(null);

  // 五个顶点 - 初始化时确保 B、A、D 共线，C、A、E 共线
  // A 为支点，B-A-D 在一条直线上，C-A-E 在另一条直线上
  // ADE 面积比 ABC 小（D、E 更靠近 A）
  const [vertices, setVertices] = useState({
    A: { x: 400, y: 250 },      // 中心点（支点）
    B: { x: 100, y: 430 },      // 左下（B-A-D 共线）
    C: { x: 700, y: 430 },      // 右下（C-A-E 共线）
    D: { x: 617, y: 120 },      // 右上（B-A-D 共线，更靠近 A）
    E: { x: 183, y: 120 }       // 左上（C-A-E 共线，更靠近 A）
  });

  const [dragging, setDragging] = useState(false);
  const [draggedPoint, setDraggedPoint] = useState(null);

  // 固定工作空间尺寸
  const WORKSPACE_WIDTH = 800;
  const WORKSPACE_HEIGHT = 500;

  // 单位转换：每100像素 = 3单位
  const SCALE = 3 / 100;

  // 计算距离（像素）
  const calculateDistance = (p1, p2) => {
    const dx = p2.x - p1.x;
    const dy = p2.y - p1.y;
    return Math.sqrt(dx * dx + dy * dy);
  };

  // 计算三角形面积（使用叉积，像素²）
  const calculateTriangleArea = (p1, p2, p3) => {
    const area = Math.abs(
      (p2.x - p1.x) * (p3.y - p1.y) - (p3.x - p1.x) * (p2.y - p1.y)
    ) / 2;
    return area;
  };

  // 计算常量（转换为单位）
  const AE = calculateDistance(vertices.A, vertices.E) * SCALE;
  const DE = calculateDistance(vertices.D, vertices.E) * SCALE;
  const AD = calculateDistance(vertices.A, vertices.D) * SCALE;
  const S1 = calculateTriangleArea(vertices.A, vertices.D, vertices.E) * SCALE * SCALE;

  const AB = calculateDistance(vertices.A, vertices.B) * SCALE;
  const AC = calculateDistance(vertices.A, vertices.C) * SCALE;
  const BC = calculateDistance(vertices.B, vertices.C) * SCALE;
  const S2 = calculateTriangleArea(vertices.A, vertices.B, vertices.C) * SCALE * SCALE;

  // 绘制画布
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const windowWidth = window.innerWidth;
    const windowHeight = window.innerHeight;
    const isLandscape = windowWidth > windowHeight;
    let displayWidth, displayHeight;
    
    const referenceSize = isLandscape ? windowHeight : windowWidth;
    
    if (referenceSize <= 375) {
      displayWidth = 360;
      displayHeight = 225;
    } else if (referenceSize <= 560) {
      const ratio = (referenceSize - 375) / (560 - 375);
      displayWidth = Math.round(360 + ratio * (560 - 360));
      displayHeight = Math.round(225 + ratio * (350 - 225));
    } else {
      displayWidth = WORKSPACE_WIDTH;
      displayHeight = WORKSPACE_HEIGHT;
    }
    
    const dpr = window.devicePixelRatio || 1;
    canvas.width = displayWidth * dpr;
    canvas.height = displayHeight * dpr;
    canvas.style.width = `${displayWidth}px`;
    canvas.style.height = `${displayHeight}px`;
    
    const ctx = canvas.getContext('2d');
    ctx.scale(dpr, dpr);
    
    if (displayWidth !== WORKSPACE_WIDTH) {
      const scale = displayWidth / WORKSPACE_WIDTH;
      ctx.scale(scale, scale);
    }
    
    // 清空画布
    ctx.clearRect(0, 0, WORKSPACE_WIDTH, WORKSPACE_HEIGHT);
    
    // 绘制背景
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(0, 0, WORKSPACE_WIDTH, WORKSPACE_HEIGHT);

    const { A, B, C, D, E } = vertices;

    // 绘制三角形 ABC（下面的三角形）
    ctx.fillStyle = 'rgba(76, 175, 80, 0.1)';
    ctx.beginPath();
    ctx.moveTo(A.x, A.y);
    ctx.lineTo(B.x, B.y);
    ctx.lineTo(C.x, C.y);
    ctx.closePath();
    ctx.fill();

    ctx.strokeStyle = '#4CAF50';
    ctx.lineWidth = 3;
    ctx.stroke();

    // 绘制三角形 ADE（上面的三角形）
    ctx.fillStyle = 'rgba(33, 150, 243, 0.1)';
    ctx.beginPath();
    ctx.moveTo(A.x, A.y);
    ctx.lineTo(D.x, D.y);
    ctx.lineTo(E.x, E.y);
    ctx.closePath();
    ctx.fill();

    ctx.strokeStyle = '#2196F3';
    ctx.lineWidth = 3;
    ctx.stroke();

    // 绘制辅助线 BD 和 CE（实线）
    ctx.strokeStyle = '#FF9800';
    ctx.lineWidth = 2;

    // 绘制 BD
    ctx.beginPath();
    ctx.moveTo(B.x, B.y);
    ctx.lineTo(D.x, D.y);
    ctx.stroke();

    // 绘制 CE
    ctx.beginPath();
    ctx.moveTo(C.x, C.y);
    ctx.lineTo(E.x, E.y);
    ctx.stroke();

    // 绘制顶点
    const drawVertex = (point, label, color) => {
      ctx.beginPath();
      ctx.arc(point.x, point.y, 8, 0, Math.PI * 2);
      ctx.fillStyle = color;
      ctx.fill();
      ctx.strokeStyle = '#fff';
      ctx.lineWidth = 2;
      ctx.stroke();

      // 绘制标签
      ctx.font = 'bold 16px Arial';
      ctx.fillStyle = color;
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      
      const offset = 20;
      let labelX = point.x;
      let labelY = point.y - offset;

      if (label === 'B') {
        labelX = point.x - offset;
        labelY = point.y + offset;
      } else if (label === 'C') {
        labelX = point.x + offset;
        labelY = point.y + offset;
      } else if (label === 'D') {
        labelX = point.x + offset;
        labelY = point.y - offset;
      } else if (label === 'E') {
        labelX = point.x - offset;
        labelY = point.y - offset;
      }

      ctx.fillText(label, labelX, labelY);
    };

    drawVertex(A, 'A', '#FF6B6B');
    drawVertex(B, 'B', '#4CAF50');
    drawVertex(C, 'C', '#4CAF50');
    drawVertex(D, 'D', '#2196F3');
    drawVertex(E, 'E', '#2196F3');

  }, [vertices]);

  // 获取画布坐标
  const getCanvasCoords = (e) => {
    const canvas = canvasRef.current;
    if (!canvas) return { x: 0, y: 0 };

    const rect = canvas.getBoundingClientRect();

    const clientX = e.touches ? e.touches[0].clientX : e.clientX;
    const clientY = e.touches ? e.touches[0].clientY : e.clientY;

    // 检查是否是小屏幕旋转模式
    const isSmallScreen = window.innerWidth <= 480;

    if (isSmallScreen) {
      // 小屏幕旋转模式：容器旋转了90度（顺时针）
      // canvas的getBoundingClientRect()返回的是旋转后在屏幕上的实际位置

      // 计算点击位置相对于canvas的位置（在屏幕坐标系中）
      const relativeX = clientX - rect.left;
      const relativeY = clientY - rect.top;

      // 旋转90度（顺时针）的逆变换
      // 旋转90度：原坐标(x, y) -> 旋转后(y, -x)
      // 逆变换：旋转后坐标(x', y') -> 原坐标(-y', x')
      // 但由于Y轴方向（向下为正），实际变换为：
      const originalX = relativeY;
      const originalY = rect.width - relativeX;

      // 根据当前画布尺寸，将坐标映射回原始工作空间
      // 注意：旋转后canvas的显示宽度是rect.height，高度是rect.width
      const scale = rect.height / WORKSPACE_WIDTH;

      return {
        x: originalX / scale,
        y: originalY / scale
      };
    }

    // 正常模式：原有逻辑
    // 计算相对于canvas的坐标
    const relativeX = clientX - rect.left;
    const relativeY = clientY - rect.top;

    // 根据当前画布尺寸，将坐标映射回原始工作空间
    const windowWidth = window.innerWidth;
    const windowHeight = window.innerHeight;
    const isLandscape = windowWidth > windowHeight;
    const referenceSize = isLandscape ? windowHeight : windowWidth;

    let scale = 1;

    if (referenceSize <= 375) {
      scale = 360 / WORKSPACE_WIDTH;
    } else if (referenceSize <= 560) {
      const ratio = (referenceSize - 375) / (560 - 375);
      const displayWidth = Math.round(360 + ratio * (560 - 360));
      scale = displayWidth / WORKSPACE_WIDTH;
    }

    return {
      x: relativeX / scale,
      y: relativeY / scale
    };
  };

  // 检查是否点击了某个顶点（只有 E 和 C 可以拖动）
  const getClickedPoint = (x, y) => {
    const threshold = 20;
    const E = vertices.E;
    const C = vertices.C;

    // 检查 E
    let dx = x - E.x;
    let dy = y - E.y;
    if (Math.sqrt(dx * dx + dy * dy) < threshold) {
      return 'E';
    }

    // 检查 C
    dx = x - C.x;
    dy = y - C.y;
    if (Math.sqrt(dx * dx + dy * dy) < threshold) {
      return 'C';
    }

    return null;
  };

  // 鼠标按下
  const handleMouseDown = (e) => {
    const coords = getCanvasCoords(e);
    const point = getClickedPoint(coords.x, coords.y);
    if (point) {
      setDragging(true);
      setDraggedPoint(point);
    }
  };

  // 鼠标移动
  const handleMouseMove = (e) => {
    if (!dragging || !draggedPoint) return;

    const coords = getCanvasCoords(e);
    const A = vertices.A;

    // E 在水平方向滑动
    if (draggedPoint === 'E') {
      const B = vertices.B;

      // E 不能越过 B（E.x 不能小于 B.x）
      const constrainedEX = Math.max(B.x, coords.x);
      const newE = { x: constrainedEX, y: vertices.E.y };

      // 计算 C 的位置：C、A、E 三点共线（共线优先级最高）
      // 直线方程：从 E 经过 A 到 C
      // 方向向量：(A.x - E.x, A.y - E.y)
      const dirX = A.x - newE.x;
      const dirY = A.y - newE.y;

      // C 在 y = 430 的水平线上
      // 参数方程：x = A.x + t * dirX, y = A.y + t * dirY
      // 当 y = 430 时，t = (430 - A.y) / dirY
      const t = (vertices.C.y - A.y) / dirY;
      let newC = {
        x: A.x + t * dirX,
        y: vertices.C.y
      };

      // C 不能越过 B（C.x 不能小于 B.x）
      if (newC.x < B.x) {
        // 如果 C 会越过 B，则限制 C 在 B.x，反向计算 E 的位置
        newC = { x: B.x, y: vertices.C.y };

        // 重新计算 E 的位置以保持共线
        const dirX2 = A.x - newC.x;
        const dirY2 = A.y - newC.y;
        const t2 = (vertices.E.y - A.y) / dirY2;
        const recalcE = {
          x: A.x + t2 * dirX2,
          y: vertices.E.y
        };

        setVertices(prev => ({
          ...prev,
          E: recalcE,
          C: newC
        }));
      } else {
        setVertices(prev => ({
          ...prev,
          E: newE,
          C: newC
        }));
      }
    }
    // C 在水平方向滑动
    else if (draggedPoint === 'C') {
      const B = vertices.B;

      // C 不能越过 B（C.x 不能小于 B.x）
      const constrainedCX = Math.max(B.x, coords.x);
      const newC = { x: constrainedCX, y: vertices.C.y };

      // 计算 E 的位置：C、A、E 三点共线（共线优先级最高）
      // 直线方程：从 C 经过 A 到 E
      // 方向向量：(A.x - C.x, A.y - C.y)
      const dirX = A.x - newC.x;
      const dirY = A.y - newC.y;

      // E 在 y = 120 的水平线上
      // 参数方程：x = A.x + t * dirX, y = A.y + t * dirY
      // 当 y = 120 时，t = (120 - A.y) / dirY
      const t = (vertices.E.y - A.y) / dirY;
      let newE = {
        x: A.x + t * dirX,
        y: vertices.E.y
      };

      // E 不能越过 B（E.x 不能小于 B.x）
      if (newE.x < B.x) {
        // 如果 E 会越过 B，则限制 E 在 B.x，反向计算 C 的位置
        newE = { x: B.x, y: vertices.E.y };

        // 重新计算 C 的位置以保持共线
        const dirX2 = A.x - newE.x;
        const dirY2 = A.y - newE.y;
        const t2 = (vertices.C.y - A.y) / dirY2;
        const recalcC = {
          x: A.x + t2 * dirX2,
          y: vertices.C.y
        };

        setVertices(prev => ({
          ...prev,
          C: recalcC,
          E: newE
        }));
      } else {
        setVertices(prev => ({
          ...prev,
          C: newC,
          E: newE
        }));
      }
    }
    // B、D、A 不可拖动
  };

  // 鼠标释放
  const handleMouseUp = () => {
    setDragging(false);
    setDraggedPoint(null);
  };

  // 重置
  const handleReset = () => {
    setVertices({
      A: { x: 400, y: 250 },
      B: { x: 100, y: 430 },
      C: { x: 700, y: 430 },
      D: { x: 617, y: 120 },
      E: { x: 183, y: 120 }
    });
  };

  return (
    <div className="geometry-model-view full-screen">
      <div className="main-container">
        {/* 顶部：Logo 和标题（带背景） */}
        <div className="top-bar">
          <button
            onClick={() => navigate('/')}
            className="back-button"
            aria-label="返回列表"
          >
            <ArrowLeft size={20} />
            <span className="back-text">返回</span>
          </button>
          <h1 className="app-title">{modelTitle || '两个三角形的交点'}</h1>
          <img src="/geometry/logo.png" alt="Logo" className="app-logo" />
        </div>

        {/* 主体内容：左中右三栏 */}
        <div className="special-model-content">
        {/* 左侧常量监控面板 */}
        <div className="special-model-info">
          <div className="constant-item">
            <span className="constant-label">a</span>
            <span className="constant-equals"> = </span>
            <span className="constant-value">{DE.toFixed(2)}</span>
          </div>
          <div className="constant-item">
            <span className="constant-label">e</span>
            <span className="constant-equals"> = </span>
            <span className="constant-value">{AD.toFixed(2)}</span>
          </div>
          <div className="constant-item">
            <span className="constant-label">c</span>
            <span className="constant-equals"> = </span>
            <span className="constant-value">{AE.toFixed(2)}</span>
          </div>
          <div className="constant-item">
            <span className="constant-label">S<sub>1</sub></span>
            <span className="constant-equals"> = </span>
            <span className="constant-value">{S1.toFixed(2)}</span>
          </div>
          <div className="constant-item">
            <span className="constant-label">b</span>
            <span className="constant-equals"> = </span>
            <span className="constant-value">{BC.toFixed(2)}</span>
          </div>
          <div className="constant-item">
            <span className="constant-label">d</span>
            <span className="constant-equals"> = </span>
            <span className="constant-value">{AC.toFixed(2)}</span>
          </div>
          <div className="constant-item">
            <span className="constant-label">f</span>
            <span className="constant-equals"> = </span>
            <span className="constant-value">{AB.toFixed(2)}</span>
          </div>
          <div className="constant-item">
            <span className="constant-label">S<sub>2</sub></span>
            <span className="constant-equals"> = </span>
            <span className="constant-value">{S2.toFixed(2)}</span>
          </div>
        </div>

        {/* 中间画布区 */}
        <div className="special-model-canvas-wrapper">
          <canvas
            ref={canvasRef}
            className="special-model-canvas"
            onMouseDown={handleMouseDown}
            onMouseMove={handleMouseMove}
            onMouseUp={handleMouseUp}
            onMouseLeave={handleMouseUp}
            onTouchStart={handleMouseDown}
            onTouchMove={handleMouseMove}
            onTouchEnd={handleMouseUp}
          />
        </div>

        {/* 右侧控制面板 */}
        <div className="special-model-controls">
          <button
            className="btn"
            onClick={handleReset}
          >
            重置
          </button>
        </div>
      </div>

      {/* 下方表达式提示 */}
      <div className="special-model-footer">
        {/* 左侧：边长比例 */}
        <div className="expression-group">
          <div className="fraction-row">
            <div className="fraction">
              <div className="fraction-numerator">c</div>
              <div className="fraction-line"></div>
              <div className="fraction-denominator">d</div>
            </div>
            <span className="equals">=</span>
            <div className="fraction">
              <div className="fraction-numerator">a</div>
              <div className="fraction-line"></div>
              <div className="fraction-denominator">c</div>
            </div>
            <span className="equals">=</span>
            <div className="fraction">
              <div className="fraction-numerator">e</div>
              <div className="fraction-line"></div>
              <div className="fraction-denominator">f</div>
            </div>
            <span className="equals"></span>
            <span className="result">{(AE / AC).toFixed(3)}</span>
          </div>
        </div>

        {/* 右侧：面积比例 */}
        <div className="expression-group">
          <div className="fraction-row">
            <div className="fraction">
              <div className="fraction-numerator">S<sub>1</sub></div>
              <div className="fraction-line"></div>
              <div className="fraction-denominator">S<sub>2</sub></div>
            </div>
            <span className="equals">=</span>
            <div className="fraction">
              <div className="fraction-numerator">c²</div>
              <div className="fraction-line"></div>
              <div className="fraction-denominator">d²</div>
            </div>
            <span className="equals">=</span>
            <div className="fraction">
              <div className="fraction-numerator">a²</div>
              <div className="fraction-line"></div>
              <div className="fraction-denominator">b²</div>
            </div>
            <span className="equals">=</span>
            <div className="fraction">
              <div className="fraction-numerator">e²</div>
              <div className="fraction-line"></div>
              <div className="fraction-denominator">f²</div>
            </div>
            <span className="equals"></span>
            <span className="result">{((AE / AC) * (AE / AC)).toFixed(3)}</span>
          </div>
        </div>
      </div>
      </div>
    </div>
  );
}

export default TwoTrianglesIntersection;

